import os
import time
import datetime


# 不能导入MyLogger,因为会引起 a circular import
# fmtDict={
#     "HMS":"%H:%M:%S",
#     "mdHM":"%m%d%H%M",
#     "HM":"%H%M",
#     "sss":"%f",
#     "":"",
#     "":"",
#     "":"",
#     "":""
# }
from Config import Params


def timeStr2stampS(timeStr,fmt=None):
    if fmt==None:
        return int(time.mktime(time.strptime(timeStr, '%Y-%m-%d %H:%M:%S')))
    else:
        return int(time.mktime(time.strptime(timeStr, fmt)))
def engTimeStr2ChnTimeStr(timeStr:str):
    return stampS2TimeStr(timeStr2stampS(timeStr,fmt="%a, %d %b %Y %H:%M:%S GMT"))

def timeStr2stampS000(timeStr):
    return int(datetime.datetime.strptime(timeStr, '%Y-%m-%d %H:%M:%S').timestamp() * 1000)


def timeStr2stamp13(timeStr):
    return int(datetime.datetime.strptime(timeStr, '%Y-%m-%d %H:%M:%S.%f').timestamp() * 1000)


def stampS2TimeStr(stamp10, fmt=""):
    if fmt == "":
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp10))
    elif fmt == "HMS":
        return time.strftime("%H:%M:%S", time.localtime(stamp10))
    elif fmt == "mdHM":
        return time.strftime("%m%d%H%M", time.localtime(stamp10))
    elif fmt == "HM":
        return time.strftime("%H%M", time.localtime(stamp10))
    elif fmt == "sss":
        return time.strftime("%f", time.localtime(stamp10))
    elif fmt == "y-m-d H:M:S.sss":
        return (datetime.datetime.fromtimestamp(stamp10 / 1)).strftime("%Y-%m-%d %H:%M:%S.%f")
    elif fmt == "mdHMS":
        return (datetime.datetime.fromtimestamp(stamp10 / 1)).strftime("%m%d%H%M%S")


def getFormatTimeByStampOrStr(stampOrStr, format="%Y-%m-%d %H:%M:%S"):
    if isinstance(stampOrStr, str):
        stampOrStr = timeStr2stampS(stampOrStr)
        return getFormatTimeByStampOrStr(stampOrStr, format)
    elif isinstance(stampOrStr, int):
        if format == "ymdHMSsss":
            return (datetime.datetime.fromtimestamp(stampOrStr / 1000)).strftime("%Y-%m-%d %H:%M:%S.%f")
        else:
            return time.strftime(format, time.localtime(stampOrStr))
    else:
        pass
        pass #2204# print("unKnown type")
    return


def stampS2TimeStr2(stamp10):
    return time.strftime("%m%d%H%M", time.localtime(stamp10))


def stamp132TimeStr(stamp13):
    # return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stamp13/1000))
    return (datetime.datetime.fromtimestamp(stamp13 / 1000)).strftime("%Y-%m-%d %H:%M:%S.%f")


def getStamp10(offset=0):
    return round(time.time()) + offset


def getStamp13(offset=0, is000=False):
    if not is000:
        return round(time.time() * 1000) + offset
    else:
        return int(time.time()) * 1000 + offset


def getFormatTimeToday(offset=0):
    if offset == 0:
        return time.strftime("%Y-%m-%d", time.localtime())
    else:
        return time.strftime("%Y-%m-%d", time.localtime(int(time.time()) + 60 * 60 * 24 * offset))


def getFormatTimeNow(format=""):
    if format == "":
        return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    else:
        return time.strftime(format, time.localtime())


def getFormatMinuteNow():
    return time.strftime("%Y-%m-%d %H:%M", time.localtime())


def getMilliSecondNow():
    time.sleep(0.01)
    return str(round(time.time() * 1000 % 1000)).zfill(3)


def getFormatHourNow():
    return time.strftime("%Y-%m-%d %H", time.localtime())


# def getFormatNextMinute():
#     return getFormatHourNow()+":"+str(time.localtime().tm_min+1)
# def getFormatMinutesLater(n):
#     return getFormatHourNow()+":"+str(time.localtime().tm_min+n)
def getStamp10MinutesLater(n):
    return int(time.time()) // 60 * 60 + n * 60


def getFormatTimeLater(n):
    return stampS2TimeStr(int(time.time()) // 60 * 60 + n * 60)


def getFormatMinutesLater(n):
    return time.strftime("%Y-%m-%d %H:%M", time.localtime(int(time.time()) // 60 * 60 + round(n * 60)))


def getFormatSecondsLater(n):
    return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(int(time.time()) + round(n * 1)))


def spanBetweenDate(dateStr1: str, dateStr2: str):
    return spanBetweenStamp(timeStr2stampS(dateStr1),timeStr2stampS(dateStr2))
def getYearFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split("-")[0])
def getMonthFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split("-")[1])
def getDayFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split(" ")[0].split("-")[-1])
def getHourFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split(" ")[1].split(":")[0])
def getMinuteFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split(":")[-2])
def getSecondFromTimeStr(timeStr=None):
    if timeStr==None:
        timeStr = getFormatTimeNow()
    return int(timeStr.split(":")[-1])


def spanBetweenStamp(stamp1: int, stamp2: int): # stamp为10位
    diff = stamp2 - stamp1
    if diff >= 86400:
        return str(diff // 86400) + "天" + str(diff % 86400 // 3600) + "时"  # 向下取整
    else:
        return str(diff // 3600) + "时" + str(diff % 3600 // 60) + "分"  # 向下取整


if __name__ == '__main__':
    # log.info(stampS2TimeStr2(int(time.time())))
    pass #2204# print(stampS2TimeStr(int(time.time()), "mdHMS"))
    pass #2204# print(stampS2TimeStr(int(time.time()), "y-m-d H:M:S.sss"))
    # log.info(timeStr2stamp13('2022-04-13 11:33:02.345678'))
    # log.info(getFormatTimeLater(5))
    # log.info(getStamp10MinutesLater(5))
    # ss = str(int(time.time() * 1000) % 1000).zfill(3)
    # pass #2204# print(ss)
    #
    # res = spanBetweenDate("2022-12-25 12:00:00","2022-12-27 22:30:20")
    #
    # # 44152.0146412037
    # # DateObj = datetime(year=1900, month=1, day=1)
    # # DateObj += datetime.timedelta(days=44976.0006944444)  # 转换datetime格式，这里的datetime就是float，值为上面注释的
    # # dateTime = DateObj.strftime("%Y/%m/%d %H:%M:%S")
    # print(time.time())
    # # print(timeStr2stampS())
    #
    # pass #2204# print("res:",res)
    # res = getStamp10MinutesLater(3)
    # print(res)
    # %Y-%m-%d %H:%M:%S
    # ss = engTimeStr2ChnTimeStr("Mon, 06 Mar 2023 06:25:38 GMT")
    # print(ss)
    # print("yzprt globals():", globals())
    # print("yzprt args:", vars())
    # hPath = os.environ['hPath']
    # print("yzprt iPath:", iPath)
    # myPara = int(os.environ['myPara'])
    # print("yzprt myPara:", myPara)
    # while True:
    #     if getStamp10()%myPara==0:
    #         print(myPara,":",getFormatTimeNow())
    #     time.sleep(1)
    filePath = os.path.join(Params.ROOT_DIR,"Utils/TimeUtil.py")
    with open(filePath,'r',encoding='utf-8',errors='ignore') as f:
        ss = f.read()
        print("yzprt ss:", ss)
    distPath = os.path.join(Params.ROOT_DIR, "Test/test_TimeUtil_01.py")
    with open(distPath, 'w', encoding='utf-8', errors='ignore') as f:
        ss = f.write(ss.replace('print("yzprt iPath:", iPath)','print("yzprt iPath:", iPath)'))
